<!--  -->
<template>
  <div class='authority'>
    <el-button v-permissions="'deviceGroup:add'" type="primary" @click="addGroupNow" style="margin-bottom: 10px;">
      新增
    </el-button>
    <!-- 查询 -->
    <el-form :inline="true" :model="FindFromForGroup" class="demo-form-inline">
      <el-form-item label="关键字">
        <el-input v-model="FindFromForGroup.kw" placeholder="请输入关键字"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitSrearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表展示 -->
    <div>
      <el-table
        :data="getMyGroupList"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="55">
        </el-table-column>
        <el-table-column
          prop="groupNum"
          label="批次"
          width="180">
        </el-table-column>
        <el-table-column
          prop="switchName"
          label="开关"
          width="180">
        </el-table-column>
        <el-table-column
          prop="tahName"
          label="温湿度设备名称"
          width="180">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          >
          <template slot-scope="scope">
            <el-button v-permissions="'deviceGroup:update'" @click="updateGroupDetail(scope.row.groupNum,scope.row.tahId)" type="text" size="small">修改</el-button>
            <el-button v-permissions="'deviceGroup:detail'" @click="openGroupDetails(scope.row.groupNum)" type="text" size="small">详情</el-button>
            <el-button v-permissions="'deviceGroup:delete'" @click="deletRoleUser(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增组合设备 -->
    <el-dialog
      title="新增设备组合"
      :visible.sync="addGroupShow"
      :close-on-press-escape="false"
      @close="closeDia"
      width="90%">
      <div class="outSideBox">
        <SwitchSwiper
          :tagTitle="tagTileForDevice"
          :swiperTitle="swiperDeviceTitle"
          :tableList="tableListForswicthDevice"
          :total="tatalForSwitchDevice"
          @handleCurrentChange="getListForSwitchDevice"/>
        <DeviceSwiper
          :tableList="tableSwitchForTah"
          :total="tatalForTah"
          @handleCurrentChange="getListforTah"
          :DigTitle="DigTitle"/>
      </div>
      <div style="width: 100%; height: auto; margin-top: 10px; text-align: center;">
        <el-button type="primary" @click="commitDevice('add')">
          保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      title="修改设备组合"
      :visible.sync="updateGroupShow"
      :close-on-press-escape="false"
      @close="closeDia"
      width="90%">
      <div class="outSideBox">
        <SwitchSwiper
          :tagTitle="tagTileForDevice"
          :swiperTitle="swiperDeviceTitle"
          :tableList="tableListForswicthDevice"
          :total="tatalForSwitchDevice"
          @handleCurrentChange="getListForSwitchDevice"/>
        <DeviceSwiper
          :tableList="tableSwitchForTah"
          :total="tatalForTah"
          :defaultCheckedNum="defaultCheckedNum"
          @handleCurrentChange="getListforTah"
          :DigTitle="DigTitle"/>
      </div>
      <div style="width: 100%; height: auto; margin-top: 10px; text-align: center;">
        <el-button type="primary" @click="commitDevice('update')">
          保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog
      title="设备组合详情"
      :visible.sync="showDetails"
      @close="showDetails = false"
      width="60%">
      <div>
        <el-table
          :data="tableDetailData"
          style="width: 100%"
          max-height="250">
          <el-table-column
            fixed
            prop="tahName"
            label="设备名称"
            width="150" />
          <el-table-column
            fixed
            prop="switchName"
            label="开关名称"
            width="150" />
          <el-table-column
            fixed
            prop="switchDefStatus"
            label="默认开关状态"
            width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.switchDefStatus === 1 ? '开' : '关'}}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed
            prop="switchType"
            label="开关类型"
            width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.switchType === 0 ? '无' : scope.row.switchType === 1 ? '温度' : '湿度' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <pagination
      class="pagination_container"
      :total="pagination.total"
      :page-sizes="[10, 20, 50, 100]"
      :page.sync="pagination.page"
      :limit.sync="pagination.pageSize"
      @pagination="getGroupListForTable"
    />
  </div>
</template>

<script>
import SwitchSwiper from '@/components/SwitchSwiper'
import DeviceSwiper from '@/components/deviceSwiper'
import { switchDeviceList } from '@/api/switchDevice'
import { tahDeviceList } from '@/api/tahDevice'
import { deviceGroupAdd, deviceGroupList, deviceGroupDetail, deviceGroupUpdate } from '@/api/deviceGroup'
import Pagination from '@/components/pagination'
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    SwitchSwiper,
    Pagination,
    DeviceSwiper
  },
  data () {
    // 这里存放数据
    return {
      // 修改
      defaultCheckedNum: 0,
      updateGroupShow: false,
      recordsGroupNum: 0,
      // end
      // 详情
      showDetails: false,
      tableDetailData: [],
      // end
      // 分页
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      // 新增
      getMyGroupList: [],
      DigTitle: '温度湿度设备',
      swiperDeviceTitle: '开关设备',
      tagTileForDevice: 'device',
      addGroupShow: false,
      tableListForswicthDevice: [],
      tableSwitchForTah: [],
      tatalForSwitchDevice: 0,
      tatalForTah: 0,
      FindFromForGroup: {
        kw: ''
      }
    }
  },
  // 离开页面
  beforeRouteLeave (to, from, next) {
    sessionStorage.removeItem(`setItem${this.tagTileForDevice}`)
    next()
  },
  // 进入页面
  beforeRouteEnter (to, from, next) {
    next()
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    /**
    * 修改设备组合
    *
    */
    updateGroupDetail (val1, val2) {
      this.recordsGroupNum = val1
      deviceGroupDetail(val1).then(res => {
        if (res.code === '200') {
          const arr = res.data
          const nullArr = []
          for (const item of arr) {
            const obj = {
              switchId: item.switchId,
              switchDefStatus: item.switchDefStatus,
              switchType: item.switchType,
              tahId: item.tahId,
              closeCron: item.switchCloseCron === null ? '' : item.switchCloseCron,
              openCron: item.switchOpenCron === null ? '' : item.switchOpenCron
            }
            nullArr.push(obj)
          }
          console.log(nullArr)
          this.updateGroupShow = true
          this.defaultCheckedNum = val2
          sessionStorage.setItem('currentTah', val2)
          sessionStorage.setItem(`setItem${this.tagTileForDevice}`, JSON.stringify(nullArr))
          setTimeout(() => {
            this.getListforTah()
            this.getListForSwitchDevice()
          }, 0)
        }
      })
    },
    // end
    // 组合详情
    openGroupDetails (val) {
      deviceGroupDetail(val).then(res => {
        if (res.code === '200') {
          this.showDetails = true
          this.tableDetailData = res.data
        }
      })
    },
    // 关闭修改
    closeUpdate () {
      this.updateGroupShow = false
    },
    // 组合列表
    getGroupListForTable () {
      deviceGroupList({
        kw: this.FindFromForGroup.kw,
        limit: this.pagination.pageSize,
        page: this.pagination.page
      }).then(res => {
        if (res.code === '200') {
          this.getMyGroupList = res.data.records
          if (res.data.total > 0 && Math.ceil(res.data.total / this.pagination.size) < this.pagination.page) {
            this.pagination.page = Math.ceil(res.data.total / this.pagination.size)
            this.getCompanyListInit()
          } else {
            this.pagination.total = res.data.total
          }
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          })
        }
      })
    },
    // 获取开关设备列表
    getListForSwitchDevice (val1 = 6, val2 = 1) {
      const result = JSON.parse(sessionStorage.getItem(`setItem${this.tagTileForDevice}`)) || []
      switchDeviceList({
        limit: val1,
        page: val2
      }).then(res => {
        const deviceArr = res.data.records
        for (const item of deviceArr) {
          item.checked = false
          for (const itemRes of result) {
            if (itemRes.switchId === undefined) {
              if (item.switchId === itemRes) {
                item.checked = true
              }
            } else {
              if (item.ClientID === itemRes.switchId) {
                item.checked = true
              }
            }
          }
        }
        this.tableListForswicthDevice = deviceArr
        this.tatalForSwitchDevice = res.data.total
      })
    },
    // 获取温度湿度列表
    getListforTah (val1 = 6, val2 = 1) {
      tahDeviceList({
        limit: val1,
        page: val2
      }).then(res => {
        this.tableSwitchForTah = res.data.records
        this.tatalForTah = res.data.total
      })
    },
    // 新增 / 修改 确定
    commitDevice (val) {
      if (val === 'add') {
        const resultForAdd = JSON.parse(sessionStorage.getItem(`setItem${this.tagTileForDevice}`))
        const reultTahNum = sessionStorage.getItem('currentTah')
        for (const item of resultForAdd) {
          if (item.tahId === reultTahNum) {
            console.log('')
          } else {
            item.tahId = reultTahNum
          }
        }
        const obj = {
          groupList: resultForAdd
        }
        deviceGroupAdd(obj).then(res => {
          if (res.message === '成功') {
            this.getGroupListForTable()
            this.closeDia()
          } else {
            this.$message({
              message: res.message,
              type: 'warning'
            })
          }
        })
      } else {
        const resultForAdd = JSON.parse(sessionStorage.getItem(`setItem${this.tagTileForDevice}`))
        const reultTahNum = sessionStorage.getItem('currentTah')
        console.log(resultForAdd)
        for (const item of resultForAdd) {
          if (item.tahId === reultTahNum) {
            item.groupNum = this.recordsGroupNum
          } else {
            item.tahId = reultTahNum
            item.groupNum = this.recordsGroupNum
          }
        }
        const obj = {
          groupList: resultForAdd
        }
        deviceGroupUpdate(obj).then(res => {
          if (res.message === '成功') {
            this.getGroupListForTable()
            this.closeDia()
          } else {
            this.$message({
              message: res.message,
              type: 'warning'
            })
          }
        })
      }
    },
    // 打开新增
    addGroupNow () {
      this.addGroupShow = true
      this.getListForSwitchDevice()
      this.getListforTah()
    },
    // 关闭
    closeDia () {
      this.addGroupShow = false
      const nullArr = []
      sessionStorage.setItem(`setItem${this.tagTileForDevice}`, JSON.stringify(nullArr))
      history.go(0)
    },
    // 查询
    submitSrearch () {
      this.getGroupListForTable()
    },
    // 查询重置
    resetForm () {
      this.FindFromForGroup.kw = ''
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getGroupListForTable()
    const nullArr = []
    sessionStorage.setItem(`setItem${this.tagTileForDevice}`, JSON.stringify(nullArr))
    sessionStorage.removeItem('currentTah')
  }
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
.authority {
  width: 100%;
  height: 100%;
}
.addResult {
  width: 98%;
  border: 1px solid #000;
  padding: 5px 5px;
}
.outSideBox {
  width: 98%;
  margin-top: 10px;
  padding: 5px 5px;
  border: 1px solid #000;
  height: auto;
  max-height: 800px;
  display: grid;
  grid-template-columns: 49% 49%;
  gap: 10px;
  flex-wrap: wrap;
  overflow-y: scroll;
}
</style>
